<template>
  <view class="container">
    <!-- 地址列表 -->
    <view v-for="addr in addresses" :key="addr.id" class="address-card" :class="{ default: addr.isDefault === 1 }">
      <view class="addr-info">
        <text class="contact">{{ addr.contactName }} {{ addr.contactPhone }}</text>
        <text class="detail">{{ addr.province }}{{ addr.city }}{{ addr.district }} {{ addr.address }}</text>
      </view>
      <view class="actions">
        <button size="mini" @click="openForm('edit', addr)">编辑</button>
        <button size="mini" type="warn" @click="deleteAddress(addr.id)">删除</button>
        <button v-if="addr.isDefault !== 1" size="mini" @click="setDefault(addr.id)">设为默认</button>
        <text v-else class="default-tag">默认</text>
      </view>
    </view>

    <!-- 添加按钮 -->
    <view class="add-btn-box">
      <button class="btn-add" @click="openForm('add')">+ 添加地址</button>
    </view>

    <!-- 弹窗表单 -->
    <view v-if="showForm" class="popup-mask" @click="closeForm">
      <view class="popup" @click.stop>
        <text class="popup-title">{{ formMode === 'add' ? '新增地址' : '编辑地址' }}</text>

        <view class="form">
          <input v-model="form.contactName" placeholder="联系人姓名" class="form-input" />
          <input v-model="form.contactPhone" placeholder="联系电话" class="form-input" type="number" />

          <!-- 省份选择 -->
          <picker mode="selector" :range="provinces" @change="onProvinceChange">
            <view class="picker">省份：{{ form.province }}</view>
          </picker>

          <!-- 城市选择 -->
          <picker mode="selector" :range="cities" @change="onCityChange">
            <view class="picker">城市：{{ form.city }}</view>
          </picker>

          <!-- 区县选择 -->
          <picker mode="selector" :range="districts[form.city]" @change="onDistrictChange">
            <view class="picker">区县：{{ form.district }}</view>
          </picker>

          <input v-model="form.address" placeholder="详细地址" class="form-input" />

          <label class="default-checkbox">
            <checkbox :checked="form.isDefault === 1" @change="e => form.isDefault = e.detail.value.length ? 1 : 0" />
            设为默认地址
          </label>
        </view>

        <button class="submit-btn" @click="saveAddress">保存</button>
      </view>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request.js'

export default {
  data() {
    return {
      addresses: [],
      showForm: false,
      formMode: 'add',
      form: {
        id: null,
        contactName: '',
        contactPhone: '',
        province: '广东省',
        city: '珠海市',
        district: '香洲区',
        address: '',
        isDefault: 0
      },
      provinces: ['广东省'],
      cities: [
        '广州市','深圳市','珠海市','汕头市','佛山市','韶关市','河源市','梅州市','惠州市','汕尾市',
        '东莞市','中山市','江门市','阳江市','湛江市','茂名市','肇庆市','清远市','潮州市','揭阳市','云浮市'
      ],
      districts: {
        '广州市': ['越秀区','荔湾区','天河区','海珠区','白云区','黄埔区','花都区','番禺区','南沙区','增城区','从化区'],
        '深圳市': ['福田区','罗湖区','南山区','盐田区','宝安区','龙岗区','龙华区','坪山区','光明区'],
        '珠海市': ['香洲区','斗门区','金湾区'],
        '汕头市': ['龙湖区','金平区','濠江区','潮阳区','潮南区','澄海区','南澳县'],
        '佛山市': ['禅城区','南海区','顺德区','三水区','高明区'],
        '韶关市': ['浈江区','武江区','曲江区','乐昌市','南雄市','始兴县','仁化县','翁源县','新丰县','乳源瑶族自治县'],
        '河源市': ['源城区','紫金县','龙川县','连平县','和平县','东源县'],
        '梅州市': ['梅江区','梅县区','兴宁市','大埔县','丰顺县','五华县','平远县','蕉岭县'],
        '惠州市': ['惠城区','惠阳区','博罗县','惠东县','龙门县'],
        '汕尾市': ['城区','陆丰市','海丰县','陆河县'],
        '东莞市': ['莞城区','南城区','东城区','万江区','厚街镇','长安镇','大朗镇','塘厦镇','凤岗镇','清溪镇','樟木头镇'],
        '中山市': ['石岐区','东区','西区','南区','火炬开发区','小榄镇','古镇','三乡镇','坦洲镇','黄圃镇'],
        '江门市': ['蓬江区','江海区','新会区','台山市','开平市','鹤山市','恩平市'],
        '阳江市': ['江城区','阳春市','阳西县','阳东县'],
        '湛江市': ['赤坎区','霞山区','坡头区','麻章区','廉江市','雷州市','吴川市','遂溪县','徐闻县'],
        '茂名市': ['茂南区','电白区','化州市','信宜市','高州市'],
        '肇庆市': ['端州区','鼎湖区','高要区','四会市','广宁县','怀集县','封开县','德庆县'],
        '清远市': ['清城区','清新区','英德市','连州市','佛冈县','阳山县','连山壮族瑶族自治县','连南瑶族自治县'],
        '潮州市': ['湘桥区','潮安区','饶平县'],
        '揭阳市': ['榕城区','揭东区','普宁市','揭西县','惠来县'],
        '云浮市': ['云城区','云安区','罗定市','新兴县','郁南县']
      }
    }
  },
  onLoad() {
    this.loadAddresses()
  },
  methods: {
    async loadAddresses() {
      const user = uni.getStorageSync('user')
      const res = await request({ url: `/user-address/${user.userId}`, method: 'GET' })
      if (res.code === 200) this.addresses = res.data || []
    },
    openForm(mode, addr = null) {
      this.formMode = mode
      if (mode === 'edit' && addr) {
        this.form = { ...addr }
      } else {
        this.form = { province: '广东省', city: '珠海市', district: '香洲区', isDefault: 0 }
      }
      this.showForm = true
    },
    closeForm() { this.showForm = false },
   async saveAddress() {
  const user = uni.getStorageSync('user')
  this.form.userId = user.userId
  const url = this.formMode === 'add' ? '/user-address/save' : '/user-address/update'
  const method = this.formMode === 'add' ? 'POST' : 'PUT'
  const res = await request({ url, method, data: this.form })
  if (res.code === 200) {
    uni.showToast({ title: '保存成功', icon: 'success' })
    this.showForm = false
    this.loadAddresses()
  } else {
    // 错误提示（后端返回 msg）
    uni.showToast({ title: res.msg || '操作失败', icon: 'none' })
  }
},

   async deleteAddress(id) {
  const user = uni.getStorageSync('user')
  const res = await request({ url: `/user-address/${user.userId}/${id}`, method: 'DELETE' })
  if (res.code === 200) {
    uni.showToast({ title: '删除成功', icon: 'success' })
    this.loadAddresses()
  } else {
    uni.showToast({ title: res.msg || '删除失败', icon: 'none' })
  }
},

async setDefault(id) {
  const user = uni.getStorageSync('user')
  const res = await request({ url: `/user-address/${user.userId}/${id}/default`, method: 'PUT' })
  if (res.code === 200) {
    uni.showToast({ title: '设置成功', icon: 'success' })
    this.loadAddresses()
  } else {
    uni.showToast({ title: res.msg || '设置失败', icon: 'none' })
  }
},
    onProvinceChange(e) {
      this.form.province = this.provinces[e.detail.value]
      this.form.city = '珠海市'
      this.form.district = '香洲区'
    },
    onCityChange(e) {
      this.form.city = this.cities[e.detail.value]
      this.form.district = this.districts[this.form.city][0]
    },
    onDistrictChange(e) {
      this.form.district = this.districts[this.form.city][e.detail.value]
    }
  }
}
</script>

<style scoped>
.container { background: #f8f8f8; min-height: 100vh; padding: 20rpx; }
.address-card { background: #fff; border-radius: 12rpx; padding: 20rpx; margin-bottom: 20rpx; box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05); }
.address-card.default { border: 2rpx solid #007aff; }
.addr-info { margin-bottom: 10rpx; }
.contact { font-size: 28rpx; font-weight: 600; }
.detail { font-size: 24rpx; color: #666; display: block; margin-top: 4rpx; }
.actions { display: flex; justify-content: flex-end; gap: 20rpx; align-items: center; }
.default-tag { color: #007aff; font-size: 24rpx; }

.add-btn-box { text-align: center; margin: 30rpx 0; }
.btn-add { background: #007aff; color: #fff; border-radius: 50rpx; padding: 16rpx 50rpx; font-size: 28rpx; }

.popup-mask { position: fixed; top:0; left:0; right:0; bottom:0; background: rgba(0,0,0,0.5); display:flex; justify-content:center; align-items:center; }
.popup { background: #fff; padding: 30rpx; border-radius: 16rpx; width: 80%; }
.popup-title { font-size: 32rpx; font-weight: 600; margin-bottom: 20rpx; display:block; }
.form { display: flex; flex-direction: column; gap: 20rpx; }
.form-input { border: 1rpx solid #ddd; border-radius: 8rpx; padding: 16rpx; font-size: 28rpx; }
.picker { padding: 16rpx; border: 1rpx solid #ddd; border-radius: 8rpx; font-size: 28rpx; }
.default-checkbox { display:flex; align-items:center; font-size: 26rpx; color:#333; }
.submit-btn { background: #007aff; color: #fff; margin-top: 20rpx; border-radius: 50rpx; font-size: 30rpx; padding: 16rpx; }
</style>
